package com.webchat.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;

@Slf4j
public class AESEncryptUtil {

    /**
     * AES 加密
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * 密钥长度16
     */
    private static final int KEY_LEN = 16;

    /**
     * 填充方式 AES/CBC/PKCS5Padding
     */
    public static final String AES_CBC_PKCS5_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 加密
     *
     * @param data 原文
     * @param key 密钥
     *
     * @return
     * @throws GeneralSecurityException
     */
    public static String encrypt(String data, String key) {
        try {
            byte[] dataByte = data.getBytes(StandardCharsets.UTF_8);
            byte[] keyByte = key.getBytes(StandardCharsets.UTF_8);
            byte[] encrypt = encrypt(dataByte, keyByte);
            return new String(Base64.getEncoder().encode(encrypt));
        } catch (Exception e) {
            log.error("AES.encrypt error. data:{}", data, e);
        }
        return null;
    }

    /**
     * 加密
     *
     * @param data 需要加密的内容
     * @param key  加密密码
     *
     * @return
     */
    public static byte[] encrypt(byte[] data, byte[] key) {
        if (key.length != 16) {
            throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
        }
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_CIPHER_ALGORITHM); // 创建密码器
            IvParameterSpec iv = new IvParameterSpec(key); // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, seckey, iv); // 初始化
            byte[] result = cipher.doFinal(data);
            return result; // 加密
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("encrypt fail!", e);
        }
    }

    /**
     * 解密
     *
     * @param data 密文
     * @param key 密钥
     * @return
     * @throws GeneralSecurityException
     */
    public static String decrypt(String data, String key) {
        try {
            byte[] dataByte = Base64.getDecoder().decode(data);
            byte[] keyByte = key.getBytes("utf-8");
            byte[] decrypt = decrypt(dataByte, keyByte);
            return new String(decrypt);
        } catch (Exception e) {
            log.error("AES.decrypt error. data:{}", data, e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param data 待解密内容
     * @param key  解密密钥
     *
     * @return
     */
    public static byte[] decrypt(byte[] data, byte[] key) {
        if (key.length != 16) {
            throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
        }
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_CIPHER_ALGORITHM); // 创建密码器
            IvParameterSpec iv = new IvParameterSpec(key); // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.DECRYPT_MODE, seckey, iv); // 初始化
            byte[] result = cipher.doFinal(data);
            return result; // 解密
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("decrypt fail!", e);
        }
    }
}